<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\FangsRequest;
use App\Models\Cities;
use App\Models\Fangs;
use DB;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Elasticsearch\ClientBuilder;

class FangsController extends BaseController
{
    /**
     * Display a listing of the resource.
     * 房源列表 with 关联关系的调用
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
       
        //with 关联关系的调用
        $data = Fangs::with(['owner'])->paginate($this->pagesize);
        //指定视图模板并且赋值
        return view('admin.fangs.index',compact('data'));
    }


    //选择城市  县区
    public function citys(Request $request){
        $id = $request->get('id');
        //查询指定数据的几种方式
        //方式1
        $listData = Cities::where('pid',$id)->get(['id','name']);
        //方式2
        // $listData = DB::table('cities')->where('pid',$id)->select('id','name')->get();
        //方式3
        return $listData;
    }

    /**
     * Show the form for creating a new resource.
     * 为什么要取得关联数据  为什么不把所有的房源属性都放在房源表中 
     * 房源的基本属性是放在房源表中的    但是添加房源的时候的属性  比如  几室几厅   ， 租赁方式   都是公共的需要进行选择的
     * 所以必须要有一个房源的属性表
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data = $this->relationData();
        return view('admin.fangs.create',compact('data'));
    }

    /**
     * Store a newly created resource in storage.
     * 这里需要注意的是  当你自己定义了验证规则 需要使用withError进行返回错误    但是你使用验证器返回的   不需要自定义   因为人家已经是定义好的
     * 
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(FangsRequest $request)
    {
        $postData = $request->except(['_token','file']);
        $postData['fang_pic'] = trim($postData['fang_pic'],'#');
        if(isset($postData['fang_config'])){
            $postData['fang_config'] = implode(',', $postData['fang_config']);
        }else{
            $postData['fang_config'] = '';
        }
        $model = Fangs::create($postData);
        //设置经纬度信息
        $url = config('gaode.geocode');
        $url = sprintf($url, $postData['fang_addr'], $postData['fang_province']);
        //发起http请求
        $client = new Client([
            'timeout'  => 5
        ]);
        $response = $client->get($url);
        
        //获取数据
        $body = (string)$response->getBody();
        $arr = (array)json_decode($body);
        //如果经纬度是存在的，然后再填充经纬度信息
        if(count($arr['geocodes']) > 0){
            $arrInsert = (array)($arr['geocodes'][0]);
            $locationArr = explode(',', $arrInsert['location']);
            $model->update([
                'longitude' => $locationArr[0],
                'latitude' => $locationArr[1]
            ]);
        }

        //es数据的添加
        //得到es客户端对象
        $client = ClientBuilder::create()->setHosts(config('es.host'))->build();
        //写文档
        $params = [
            'index' => 'fang_tt',
            'type' => '_doc',
            'id' => $model->id,
            'body' => [
                'fang_name' => $model->fang_name,
                'fang_desn' => $model->fang_desn
            ]
        ];
        //添加数据到索引文档中去
        $client->index($params);
        return redirect(route('admin.fangs.create'))->with('success', '添加成功');
    }

    //上传房东身份证
    public function upfile(Request $request)
    {
        //上传文章封面
        $pic = config('up.pic');
        //如果确实文件进行文件上传
        if ($request->hasFile('file')) {
            //将文件进行上传处理
            $ret = $request->file('file')->store('', 'fangs');
            //获取文件上传的路径
            $pic = '/uploads/fangs/' . $ret;
        }
        //如果文件上传成功，将路径进行返回
        return ['status' => 0, 'url' => $pic];
    }


    //修改房源出租状态
    public function change_status(Request $request){
        $id = $request->get('id');
        $fang_status = $request->get('fang_status');
        Fangs::where('id',$id)->update(['fang_status'=>$fang_status]);
        return ['status' => 0,'msg' => '操作成功'];
    }

    //删除照片信息
    public function delpic(Request $request)
    {
        //传递过来的地址
        $pic_url = $request->get('file');
        //得到真实的地址
        $file_path = public_path() . $pic_url;
        unlink($file_path);
        return ['status' => 0, 'msg' => '删除成功'];
    }


    //创建es索引
    public function esinit(){
        //得到es客户端对象
        $client = ClientBuilder::create()->setHosts(config('es.host'))->build();
        $params = [
            'index' => 'fangsssss',
            'body' => [
                'settings' => [
                    //分区数
                    'number_of_shards' => 5,
                    //副本数
                    'number_of_replicas' => 1
                ],
            ]
        ];
        //创建索引
        // $params = [
        //     //生成索引名称
        //     'index' => 'fangs',
        //     //类型  Body
        //     'body' => [
        //         'settings' => [
        //             //分区数
        //             'number_of_shards' => 5,
        //             //副本数
        //             'number_of_replicas' => 1
        //         ],
        //         'mappings' => [
        //             '_doc' => [
        //                 '_source' => [
        //                     'enabled' => true
        //                 ],
        //                 //字段，类似表字段，设置类型
        //                 'properties' => [
        //                     'fang_name' => [
        //                         //相当于数据查询的是= 张三你好,必须找到张三你好
        //                         'type' => 'keyword'
        //                     ],
        //                     'fang_desn' => [
        //                         'type' => 'text',
        //                         //中文分词 张三你好   张三  你好  张三你好
        //                         'analyzer' => 'ik_max_word',
        //                         'search_analyzer' => 'ik_max_word'
        //                     ]
        //                 ]

        //             ]
        //         ]
        //     ]
        // ];
        // //创建索引
        $response = $client->indices()->create($params);
    }





    /**
     * Display the specified resource.
     * 
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Fangs $fang)
    {
        //获取关联数据表  [用作页面数据的循环显示]
        $data = $this->relationData();
        //获取当前房源省所包含的市
        $currentCityList = Cities::where('pid',$fang->fang_province)->get();
        //获取市下面的县
        $currentRegionList = Cities::where('pid',$fang->fang_city)->get();
        $data['currentCityList'] = $currentCityList;
        $data['currentRegionList'] = $currentRegionList;
        $data['fang'] = $fang;
        // $data['fang']['fang_conf'] = explode(',',$fang['fang_config']);
        return view('admin.fangs.edit',compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(FangsRequest $request,$id)
    {
        $postData = $request->except(['_token','file','_method']);
        $postData['fang_pic'] = trim($postData['fang_pic'],'#');
        //这里需要单独对房源配置进行处理
        if(isset($postData['fang_config'])){
            $postData['fang_config'] = implode(',',$postData['fang_config']);
        }else{
            $postData['fang_config'] = '';
        }
        //进行更新入库操作
        Fangs::where('id',$id)->update($postData);
        //设置经纬度信息
        $url = config('gaode.geocode');
        $url = sprintf($url,$postData['fang_addr'],$postData['fang_province']);
        //发起http请求
        $client = new Client([
            'timeout' => 5
        ]);
        $response = $client->get($url);
        //获取数据
        //获取数据
        $body = (string)$response->getBody();
        $arr = (array)json_decode($body);

        if (count($arr['geocodes']) > 0) {
            $arrInsert = (array)($arr['geocodes'][0]);
            $locationArr = explode(',', $arrInsert['location']);
            Fangs::where('id',$id)->update([
                'longitude' => $locationArr[0],
                'latitude' => $locationArr[1]
            ]);
        }
        //es数据的添加
        //得到es客户端对象
        $client = ClientBuilder::create()->setHosts(config('es.host'))->build();
        //写文档
        $params = [
            'index' => 'fang_tt',
            'type' => '_doc',
            'id' => $id,
            'body' => [
                'fang_name' => $postData['fang_name'],
                'fang_desn' => $postData['fang_desn']
            ]
        ];
        //添加数据到索引文档中去
        $client->index($params);
        return redirect(route('admin.fangs.edit',['id'=>$id]))->with('success', '修改成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        
    }
}
